sugarfreeApp.controller('LoginController', ['$rootScope','$scope', '$cookies', '$window', 'AuthService', function ($rootScope,$scope, $cookies, $window, AuthService) {
  "use strict";

  $scope.login = function (credentials) {
    console.log("controller.login start", $scope.credentials);
    AuthService.login(credentials).then(function (user) {
      
      $cookies.put("UID", user.id);
      $cookies.put("NAME", user.name);
      $cookies.put("LOGO", user.logo);
      $scope.errormsg = "";
      
      /*console.info("$cookies.uid",$cookies.get("UID"));
      console.info("$cookies.uname",$cookies.get("NAME"));
      console.info("$cookies.ulogo",$cookies.get("LOGO"));
      console.info('login success', $scope.credentials, user);*/
      //if(deviceName === 'pc'){
        $window.location.href = "page_index.html";
      //}else if(deviceName === 'mobile'){
      //  $window.location.href = "mpartials/page_index.html";
      //}
      
    }, function (data) {
      console.log($scope.credentials, 'login failed');
      $scope.errormsg = "登录失败，请检查用户名或密码";
      $scope.refreshCaptcha();

      if ($window.location.href.indexOf("page_index.html") > -1) {
        // redirect to main page
        $window.location.href = "index.html";
      }
    });
  };

  $scope.refreshCaptcha = function () {
    var random = (new Date()).toString();
    $scope.captchaUrl = "captcha/generate" + "?cb=" + random;
  };

  $scope.initData = function () {
    $scope.captchaUrl = "captcha/generate";

    $scope.credentials = {
      account: '',
      password: '',
      captcha: ''
    };
    
  $cookies.remove('UID');
  $cookies.remove('NAME');
  $cookies.remove('LOGO');
  };

  $scope.initData();
}]);